# -*- coding: utf-8 -*-
import json
import logging
import math
import time
from ast import literal_eval
from datetime import date, timedelta
from collections import defaultdict

from odoo import SUPERUSER_ID, _, api, Command, fields, models
from odoo.addons.stock.models.stock_move import PROCUREMENT_PRIORITIES
from odoo.addons.web.controllers.utils import clean_action
from odoo.exceptions import UserError, ValidationError
from odoo.osv import expression
from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT, format_datetime, format_date, groupby
from odoo.tools.float_utils import float_compare, float_is_zero, float_round


class StockMoveExt(models.Model):
    _inherit = 'stock.move'

    # unit_factor - bom用量
    alt_material_id = fields.Many2one('product.product', 'Alternative Material')
    alt_material_uom_id = fields.Many2one(
        'uom.uom', 'Material Unit of Measure', required=True
    )
    alt_quan_bom = fields.Float("Alternative Quantity", digits='Product Unit of Measure', default=0)
    alt_quan_done = fields.Float("Alternative Material - Issued Quantity", digits='Product Unit of Measure', default=0)

    ori_product_id = fields.Many2one('product.product', 'Product')
    ori_product_uom = fields.Many2one(
        'uom.uom', 'Unit of Measure', required=True
    )

    ori_unit_factor = fields.Float("Unit Factor", digits='Product Unit of Measure', default=0)
    ori_product_uom_qty = fields.Float("Required Quantity", digits='Product Unit of Measure', default=0)
    ori_product_qty = fields.Float("Required Quantity", digits='Product Unit of Measure', default=0)
    req_material_id = fields.Many2one('product.product', 'Product', compute='_compute_req_material_id')
    req_product_uom_qty = fields.Float("Required Quantity", digits='Product Unit of Measure', default=0,
                                       compute='_compute_req_material_id')
    is_alt = fields.Boolean("Alternative", default=False, compute='_compute_req_material_id')
    return_uom_qty = fields.Float("Returned Quantity", digits='Product Unit of Measure', default=0)
    act_issue_qty = fields.Boolean("Actual Issued Quantity", default=False, compute='_compute_req_material_id')
    issue_type = fields.Selection([
        ('issue', 'Issue'),
        ('return', 'Return'), ('normal', 'Base Move')], string='Type', compute='_compute_req_material_id')

    @api.model_create_multi
    def create(self, vals_list):
        for vals in vals_list:
            raw_material_production_id = vals.get('raw_material_production_id')
            production_id = vals.get('production_id')
            mo = raw_material_production_id or production_id
            origin = vals.get('origin')
            p = self.env['mrp.production'].search([
                ('name', '=', origin), ], limit=1)
            #
            if mo:
                # logging.info('stock.move:')
                # logging.info(p.name)
                # logging.info(p.product_qty)
                # logging.info(vals)
                if vals.get('product_id'):
                    vals['ori_product_id'] = vals.get('product_id')
                if vals.get('product_uom'):
                    vals['ori_product_uom'] = vals.get('product_uom')
                if vals.get('product_uom_qty'):
                    vals['ori_product_uom_qty'] = vals.get('product_uom_qty')
                    vals['ori_product_qty'] = vals.get('product_uom_qty')
                    if p:
                        vals['ori_unit_factor'] = vals.get('product_uom_qty') / p.product_qty
                    else:
                        vals['ori_unit_factor'] = 1
        return super().create(vals_list)

    def _compute_req_material_id(self):
        for m in self:
            m.issue_type = 'normal'
            mo = m.raw_material_production_id or m.production_id
            m.is_alt = False
            if mo:
                m.req_material_id = m.ori_product_id
                m.req_product_uom_qty = m.ori_product_uom_qty
                m.act_issue_qty = m.quantity_done - m.return_uom_qty
                m.issue_type = 'issue'
                if m.location_id.usage == 'production':
                    m.issue_type = 'return'
            else:
                m.req_material_id = m.product_id
                m.req_product_uom_qty = m.product_uom_qty
            if m.alt_material_id:
                m.is_alt = True

    # @api.onchange('picking_id')
    # def _onchange_picking_id(self):
    #     mo = self.raw_material_production_id or self.production_id
    #     logging.info('picking_id1')
    #     if mo:
    #         self.req_material_id = self.ori_product_id
    #         logging.info('picking_id')
    #         logging.info(self.picking_id)
    #         if not self.picking_id:
    #             self.update({
    #                 'quantity': self.ori_product_qty,
    #                 'quantity_done': self.ori_product_qty,
    #                 'product_id': self.ori_product_id,
    #                 'product_uom': self.ori_product_uom,
    #                 'product_uom_qty': self.ori_product_uom_qty,
    #                 'unit_factor': self.ori_unit_factor,
    #                 'partner_id': False,
    #                 'picking_id': False,
    #                 'alt_material_id': False,
    #                 'alt_material_uom_id': False,
    #                 'alt_quan_bom': False,
    #                 'alt_quan_done': False
    #             })
    # def _action_assign(self, force_qty=False):
    # picking = self.picking_id
    # self._do_unreserve() 取消保留
